package com.hd.service.code.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hd.dao.BaseDao;
import com.hd.entity.code.CodeData;
import com.hd.service.code.CodeDataService;
import com.hd.util.StringUtils;
import com.hd.util.result.PageInfo;
/**
* 数据字典
*/
@Service("codeDataService")
public class CodeDataServiceImpl implements CodeDataService {
    @Autowired
    private BaseDao<CodeData,String>codeDataDao;
    @Override
    public void save(CodeData codeData) {
    	codeData.setId(UUID.randomUUID().toString());
       codeDataDao.save(codeData);
    }

    @Override
    public void delete(String id){
      codeDataDao.delete(CodeData.class,id);
    }
       

    @Override
    public void update(CodeData codeData) {
        codeDataDao.update(codeData);
    }
    @Override
    public CodeData get(String id){
    	return codeDataDao.get(CodeData.class, id);
    }
        

    @Override
    public void selectDataGrid(PageInfo pageInfo) {
        String hql="from CodeData where 1=1 ";
        Map<String,Object>condition=pageInfo.getCondition();
        List<Object> params=new ArrayList<Object>();
       
        if(StringUtils.isNotNull(condition.get("category"))) {
        	hql+=" and category=?";
        	params.add(condition.get("category"));
        }
        if(!pageInfo.getSort().equals("")) {
            hql+=" order by "+pageInfo.getSort()+" "+pageInfo.getOrder();
        }
        List<CodeData> codeDatas=codeDataDao.findPage(hql, pageInfo.getNowpage(), pageInfo.getPagesize(),params);
        pageInfo.setRows(codeDatas);
        int total=codeDataDao.findByList(hql,params).size();
        pageInfo.setTotal(total);
    }


       @Override
       public  boolean validCode(String  code,String  category) {
           boolean b=true;//true-可用，false-占用
           if(StringUtils.isNotNull(code)&&StringUtils.isNotNull(category)) {
               String hql="from CodeData where code=? and category=?";
               List<CodeData>codeDatas=codeDataDao.find(hql,code,category);
               if(codeDatas.size()>0) {
                   b=false;
               }
           }
           return b;
       }

	@Override
	public List<CodeData> findAllByCategory(String category) {
		String hql="from CodeData where category=?";
		return codeDataDao.find(hql,category);
	}

	@Override
	public CodeData findByCategoryAndCode(String category, String code) {
		 String hql="from CodeData where code=? and category=?";
         List<CodeData>codeDatas=codeDataDao.find(hql,code,category);
         if(codeDatas.size()>0) {
             return codeDatas.get(0);
         }
		return null;
	}

}
